<template>
  <div class="seckill-order-profile-page">
    <!-- 返回按钮 -->
    <div class="back-section">
      <el-button @click="goBack" type="primary" icon="ArrowLeft">
        返回秒杀页面
      </el-button>
    </div>

    <h2>确认秒杀订单</h2>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      加载中...
    </div>

    <!-- 错误状态 -->
    <div v-else-if="!seckillGoods || Object.keys(seckillGoods).length === 0" class="error">
      未找到秒杀商品信息
    </div>

    <!-- 订单信息 -->
    <div v-else class="order-container">
      <div class="order-item">
        <div class="item-image">
          <img :src="goodsImage || '@/assets/default-goods.png'" :alt="goodsName" class="goods-image" />
        </div>
        <div class="item-details">
          <h3>{{ goodsName }}</h3>
          <p class="item-price">秒杀价: ¥{{ seckillGoods.seckill_price }}</p>
          <p class="original-price">原价: ¥{{ originalPrice }}</p>
          <div class="quantity-control">
            <span>数量: 1</span>
          </div>
        </div>
      </div>

      <!-- 收货地址部分 -->
      <div class="delivery-address-section">
        <h3>收货信息</h3>
        <el-form label-width="100px">
          <!-- 地址选择下拉框 -->
          <el-form-item label="选择收货信息">
            <el-select v-model="selectedAddressId" placeholder="请选择收货信息" style="width: 100%;">
              <el-option
                  v-for="addr in userAddresses"
                  :key="addr.id"
                  :label="formatAddress(addr)"
                  :value="addr.id">
                <span v-if="addr.is_default === 1" style="float: right; color: #ff6b00; font-size: 13px;">[默认]</span>
                <span>{{ formatAddress(addr) }}</span>
              </el-option>
            </el-select>
            <el-button @click="showAddAddressDialog" type="primary" style="margin-left: 10px;">新增收货信息</el-button>
          </el-form-item>

          <!-- 显示选中地址详情 -->
          <div v-if="selectedAddress" class="selected-address-details">
            <p><strong>收货人:</strong> {{ selectedAddress.receiver_name }}</p>
            <p><strong>联系电话:</strong> {{ selectedAddress.receiver_phone }}</p>
            <p><strong>地址:</strong> {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detail_addr }}</p>
          </div>
        </el-form>
      </div>

      <div class="order-summary">
        <div class="summary-row">
          <span>商品总价:</span>
          <span>¥{{ seckillGoods.seckill_price }}</span>
        </div>
        <div class="summary-row total">
          <span>总计:</span>
          <span>¥{{ seckillGoods.seckill_price }}</span>
        </div>
      </div>

      <div class="order-actions">
        <el-button type="danger" size="large" @click="submitOrder">
          立即秒杀
        </el-button>
      </div>
    </div>

    <!-- 新增地址对话框 -->
    <el-dialog v-model="addAddressDialogVisible" title="新增收货地址" width="500px">
      <el-form :model="newAddressForm" ref="addressFormRef" label-width="100px">
        <el-form-item label="收货人" prop="receiver_name" :rules="[{ required: true, message: '请输入收货人姓名', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.receiver_name" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="receiver_phone" :rules="[{ required: true, message: '请输入联系电话', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.receiver_phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="省份" prop="province" :rules="[{ required: true, message: '请输入省份', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.province" placeholder="请输入省份"></el-input>
        </el-form-item>

        <el-form-item label="城市" prop="city" :rules="[{ required: true, message: '请输入城市', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.city" placeholder="请输入城市"></el-input>
        </el-form-item>

        <el-form-item label="区/县" prop="district" :rules="[{ required: true, message: '请输入区/县', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.district" placeholder="请输入区/县"></el-input>
        </el-form-item>

        <el-form-item label="详细地址" prop="detail_addr" :rules="[{ required: true, message: '请输入详细地址', trigger: 'blur' }]">
          <el-input v-model="newAddressForm.detail_addr" placeholder="请输入详细地址" type="textarea"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addAddressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNewAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import seckillGoodsApi from '@/api/seckill/seckillGoods_api.js'
import goodsApi from '@/api/goods_api.js'
import deliveryAddrApi from '@/api/deliveryAddr_api.js'
import orderApi from '@/api/order_api.js'
import orderAddrApi from '@/api/orderAddr_api.js'
import { ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import loginApi from "@/api/login_api.js";
import seckill_api from "@/api/seckill/seckill_api.js";
import seckillResult_api from "@/api/seckill/seckillResult_api.js";

export default {
  name: 'SeckillOrderProfilePage',
  components: {
    ArrowLeft
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const seckillGoods = ref({})
    const goodsInfo = ref({})
    const loading = ref(false)
    const userAddresses = ref([])
    const selectedAddressId = ref('')
    const addAddressDialogVisible = ref(false)
    const addressFormRef = ref(null)
    const currentUser = ref(null)

    // 新增地址表单
    const newAddressForm = reactive({
      receiver_name: '',
      receiver_phone: '',
      province: '',
      city: '',
      district: '',
      detail_addr: '',
      user_id: 1 // 这里应该从登录用户信息中获取
    })

    // 计算属性：获取选中的地址对象
    const selectedAddress = computed(() => {
      return userAddresses.value.find(addr => addr.id === selectedAddressId.value)
    })

    // 计算属性：商品图片
    const goodsImage = computed(() => {
      return goodsInfo.value.image || '@/assets/default-goods.png'
    })

    // 计算属性：商品名称
    const goodsName = computed(() => {
      return goodsInfo.value.name || '未知商品'
    })

    // 计算属性：原价
    const originalPrice = computed(() => {
      return goodsInfo.value.price || 0
    })

    // 获取秒杀商品详情
    const fetchSeckillGoodsDetail = async (id) => {
      if (!id) return

      loading.value = true
      try {
        // 获取秒杀商品信息
        const seckillRes = await seckillGoodsApi.getSeckillGoodsById(id)
        if (seckillRes || seckillRes.data) {
          seckillGoods.value = seckillRes
          console.log('秒杀商品详情:', seckillRes)
          console.log('商品详情:', seckillGoods.value.activity_id)

          // 获取对应的商品信息
          const goodsRes = await goodsApi.getGoodsById(seckillGoods.value.goods_id)
          if (goodsRes || goodsRes.data) {
            goodsInfo.value = goodsRes
          }
        } else {
          console.error('获取秒杀商品详情失败:', seckillRes)
        }
      } catch (err) {
        console.error('获取秒杀商品详情失败:', err)
      } finally {
        loading.value = false
      }
    }

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const userRes = await loginApi.logininfo();
        currentUser.value = userRes
        return userRes
      } catch (err) {
        console.error('获取用户信息失败:', err)
        ElMessage.error('请先登录')
        router.push('/login')
        return null
      }
    }

    // 获取用户地址列表
    const fetchUserAddresses = async () => {
      const user = await fetchUserInfo()
      if (!user) return

      try {
        const userId = user.id
        const res = await deliveryAddrApi.getAddrsByUserId(userId)
        if (res || res.data) {
          userAddresses.value = res
          // 如果有地址，优先选择默认地址，否则选择第一个
          if (userAddresses.value.length > 0) {
            const defaultAddress = userAddresses.value.find(addr => addr.is_default === 1);
            if (defaultAddress) {
              selectedAddressId.value = defaultAddress.id;
            } else {
              selectedAddressId.value = userAddresses.value[0].id;
            }
          }
        }
      } catch (err) {
        console.error('获取用户地址失败:', err)
        ElMessage.error('获取地址信息失败')
      }
    }

    // 显示新增地址对话框
    const showAddAddressDialog = async () => {
      const user = await fetchUserInfo()
      if (!user) return

      // 重置表单
      Object.assign(newAddressForm, {
        receiver_name: '',
        receiver_phone: '',
        province: '',
        city: '',
        district: '',
        detail_addr: '',
        user_id: user.id
      })
      addAddressDialogVisible.value = true
    }

    // 保存新增地址
    const saveNewAddress = async () => {
      addressFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 检查用户是否已有地址，如果没有，则将新地址设为默认地址
            if (userAddresses.value.length === 0) {
              newAddressForm.is_default = 1;
            } else {
              newAddressForm.is_default = 0;
            }

            const res = await deliveryAddrApi.addAddr(newAddressForm)
            if (res || res.code === 200) {
              ElMessage.success('地址保存成功')
              addAddressDialogVisible.value = false
              // 重新获取地址列表
              await fetchUserAddresses()
            } else {
              ElMessage.error(res?.message || '地址保存失败')
            }
          } catch (err) {
            console.error('保存地址失败:', err)
            ElMessage.error('保存地址失败')
          }
        }
      })
    }

    // 格式化地址显示
    const formatAddress = (addr) => {
      return `${addr.province}${addr.city}${addr.district}${addr.detail_addr} (${addr.receiver_name})`
    }

    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }

    // 提交秒杀订单
    const submitOrder = async () => {
      if (!selectedAddress.value) {
        ElMessage.warning('请选择收货地址')
        return
      }

      if (!currentUser.value) {
        ElMessage.warning('请先登录')
        router.push('/login')
        return
      }

      if (!seckillGoods.value.id) {
        ElMessage.warning('秒杀商品信息有误')
        return
      }

      // 检查库存
      if (seckillGoods.value.stock < 1) {
        ElMessage.error('秒杀商品库存不足')
        return
      }

      // 提交秒杀订单
      // 秒杀活动id、秒杀商品id、收货地址id
      const res = await seckill_api.seckill(seckillGoods.value.activity_id,seckillGoods.value.id,selectedAddressId.value);
      console.log(seckillGoods.value.activity_id)
      console.log(seckillGoods.value.id)
      console.log(res);
      //调用秒杀结果id，获取秒杀结果
      const seckillResult = await seckillResult_api.getResultById(res);
      console.log('秒杀结果',seckillResult.result);
      if (seckillResult.result == 1){
        ElMessage.success('秒杀成功')
        await router.push(`/user/orderList`)
      } else {
        ElMessage.error('秒杀失败')
      }
    }

    // 页面加载时获取秒杀商品详情和用户地址
    onMounted(() => {
      const seckillGoodsId = route.params.id || route.query.id
      fetchSeckillGoodsDetail(seckillGoodsId)
      fetchUserAddresses()
    })

    return {
      seckillGoods,
      goodsInfo,
      loading,
      userAddresses,
      selectedAddressId,
      selectedAddress,
      addAddressDialogVisible,
      newAddressForm,
      addressFormRef,
      goBack,
      submitOrder,
      showAddAddressDialog,
      saveNewAddress,
      formatAddress,
      goodsImage,
      goodsName,
      originalPrice
    }
  }
}
</script>

<style scoped>
.seckill-order-profile-page {
  background-color: #fff;
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.back-section {
  margin-bottom: 20px;
}

.order-container {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
}

.order-item {
  display: flex;
  gap: 20px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.item-image {
  flex: 0 0 120px;
}

.goods-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

.item-details {
  flex: 1;
}

.item-details h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.item-price {
  font-size: 18px;
  color: #e64340;
  font-weight: bold;
  margin: 10px 0;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin: 5px 0;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.delivery-address-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.delivery-address-section h3 {
  margin-top: 0;
  color: #333;
}

.selected-address-details {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #eee;
}

.selected-address-details p {
  margin: 5px 0;
}

.order-summary {
  margin: 20px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
}

.summary-row.total {
  font-size: 18px;
  font-weight: bold;
  border-top: 1px solid #ddd;
  margin-top: 10px;
  padding-top: 10px;
}

.order-actions {
  text-align: right;
  margin-top: 20px;
}

.loading, .error {
  text-align: center;
  padding: 50px 20px;
  color: #999;
  font-size: 18px;
}

@media (max-width: 768px) {
  .order-item {
    flex-direction: column;
  }

  .item-image {
    flex: 0 0 auto;
  }

  .order-actions {
    text-align: center;
  }
}
</style>
